//
//  ConsoleDelegate.m
//  cTypica
//
//  Created by David Kavanagh on 11/25/08.
//  Copyright 2008 directThought. All rights reserved.
//

#import "ConsoleDelegate.h"
#import "Base64Transcoder.h"

@implementation ConsoleDelegate
@synthesize output, formatter;

+ (id)delegate {
	ConsoleDelegate *ret = [self alloc];
	ret.output = [ConsoleInfo alloc];
	ret.formatter = [[NSDateFormatter alloc] init];
	[ret.formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
	return ret;
}

// XML parser delegate methods
- (void)parser: (NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
}

- (void)parser: (NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	NSString *cleanString = [currentStringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[currentStringValue setString:@""];
	if ([elementName isEqualToString:@"instanceId"]) {
		[[self output] setInstanceId:cleanString];
	}
	else if ([elementName isEqualToString:@"timestamp"]) {
		[[self output] setTimestamp:[self.formatter dateFromString:cleanString]];
	}
	else if ([elementName isEqualToString:@"output"]) {
		int dataLen = [cleanString length];
		unsigned char dataBytes[dataLen];
		unsigned int usedLength;
		[cleanString getBytes:&dataBytes maxLength:dataLen usedLength:&usedLength encoding:NSUTF8StringEncoding
					  options:0 range:NSMakeRange(0, dataLen) remainingRange:nil];
		size_t decodedLen = EstimateBas64DecodedDataSize(dataLen);
		char decodedData[decodedLen];
		Base64DecodeData(dataBytes, dataLen, decodedData, &decodedLen);

		[[self output] setOutput:[[NSString alloc] initWithData:[NSData dataWithBytes:decodedData length: decodedLen] encoding:NSUTF8StringEncoding]];
	}
}
@end
